<template>
  <div>
    <el-button type="primary" @click="BackToShow">回显测试</el-button>
    <el-button type="primary" @click="addTest">添加测试</el-button>
    <el-dialog
      :title="
        isAdd ? '添加作战报告' : isEditView ? '查看作战报告' : '编辑作战报告'
      "
      :visible.sync="dialogOperationalReport"
      :modal-append-to-body="false"
      width="1000px"
      center
    >
      <FormCreate
        v-if="dialogOperationalReport"
        :conf="isAdded ? operationalReportConfig : editOperationalReportConfig"
        :isAdded="isAdded"
        ref="operationalReportForm"
        @submit="save"
        @reset="reset"
        @inputBoxEditCancelFiles="inputBoxEditCancelFiles"
        @editViewReport="editViewReport"
      />
    </el-dialog>
    <el-dialog
      title="图片预览"
      :width="`${lookDialogVisibleWidth}px`"
      :visible.sync="lookDialogVisible"
      append-to-body
      center
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
      <div class="btn_groups">
        <div class="cancel" @click="lookDialogVisible = false">
          <img src="@/assets/image/index/icon_cha.png" />
          <span>取消</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import operationalReportConfig from './operationalReportConfig'
import { postAddBattleReport, getReadBattleReport } from '@/api/execute'
export default {
  data() {
    return {
      operationalReportConfig,
      editOperationalReportConfig: {},
      dialogImageUrl: '',
      lookDialogVisible: false,
      dialogOperationalReport: false,
      fileList: [],
      backFileList: [],
      isAdded: null,
      isAdd: true,
      lookDialogVisibleWidth: 0,
      ImageFormat: ['png', 'jpg'],
      isEditView: true,
    }
  },
  created() {
    this.operationalReportConfig.items[2][0].attrs = {
      ...this.operationalReportConfig.items[2][0].attrs,
      onChange: this.onChange,
      onPreview: this.onPreview,
      onRemove: this.onRemove,
      onExceed: this.onExceed, // 文件超出个数限制时的钩子
    }
  },
  methods: {
    onExceed(file, fileList) {
      if (file.length + fileList.length > 5) {
        return this.$message.warning('最多上传5张图片')
      }
    },
    // true 查看 false  编辑
    editViewReport(e) {
      this.isEditView = e
    },
    addTest() {
      this.isAdded = true
      this.isAdd = true
      this.dialogOperationalReport = true
    },
    async BackToShow() {
      // let [res] = await getReadBattleReport()
      let res = {
        code: 200,
        msg: {
          desc: 'desc测试',
          title: 'title测试',
          report_type: 'report_type',
          report_id: '1234-1235',
          file_address: [
            {
              name: '02b31c535488c3d41e074e4bbb7e8c46',
              type: 'jpg',
              url: 'https://yanxuan-item.nosdn.127.net/02b31c535488c3d41e074e4bbb7e8c46.jpg',
            },
            {
              name: '09723c372699a2c5a92b2204d58bd61e',
              type: 'png',
              url: 'https://yanxuan-item.nosdn.127.net/09723c372699a2c5a92b2204d58bd61e.png',
            },
          ],
        },
      }
      this.isAdd = false
      if (res?.code == 200) {
        let { desc, title, report_type, file_address, report_id } = res.msg
        this.dialogOperationalReport = true
        this.isAdded = false
        this.editOperationalReportConfig = {
          labelWidth: '100px', //from表单的宽度
          items: [
            [
              {
                key: 'title',
                label: '作战总结',
                colspan: 24,
                type: 'input',
                value: title,
              },
            ],
            [
              {
                key: 'desc',
                label: '作战描述',
                colspan: 24,
                type: 'textarea',
                attrs: { autosize: { minRows: 7, maxRows: 15 } },
                value: desc,
              },
            ],

            [
              {
                key: 'battle_plan_id',
                label: 'battle_plan_id',
                colspan: 24,
                type: 'input',
                value: report_type,
                elColStyle: { display: 'none' },
              },
            ],
            [
              {
                key: 'report_id',
                label: 'report_id',
                colspan: 24,
                type: 'input',
                value: report_id,
                elColStyle: { display: 'none' },
              },
            ],
            [
              {
                key: 'files',
                label: '作战结果',
                colspan: 24,
                type: 'files',
                autoUpload: false,
                action: '#',
                multiple: true, //是否支持多选文件
                limit: 5, //最大允许上传个数
                attrs: {
                  headers: { 'Content-Type': 'multipart/form-data' },
                  onChange: this.onChange,
                  onPreview: this.onPreview,
                  onRemove: this.onRemove,
                  accept: '.png,.jpg,.JPG,.JPG',
                },
                value: file_address,
                // value: [],
              },
            ],
            [
              {
                key: 'tag',
                label: '动态编辑标签',
                colspan: 24,
                type: 'dynamicEditTag',
                size: 'small',
                value: ['1', '2', '123'],
                // value: [],
              },
            ],
          ],
          rules: {
            title: [
              { required: true, message: '请输入作战总结', trigger: 'blur' },
            ],
            desc: [
              { required: true, message: '请输入作战描述', trigger: 'blur' },
            ],
          },
        }
      }
    },
    reset() {
      this.dialogOperationalReport = false
    },
    /**
     * http 图片完整转字节流
     * @param {*} imageUrl http图片地址
     * @param {*} filename 图片名字
     * @param {*} fileTyp 图片类型
     */
    imageUrlToBase64(imageUrl, filename, fileType) {
      return new Promise((resolve, reject) => {
        let image = new Image() // 一定要设置为let，不然图片不显示
        image.crossOrigin = 'anonymous' //添加此行anonymous必须小写
        image.setAttribute('crossOrigin', 'anonymous') // 解决跨域问题
        image.src = imageUrl
        image.onload = () => {
          var cvs = document.createElement('canvas')
          cvs.width = image.width
          cvs.height = image.height
          var context = cvs.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          var quality = 0.8
          var dataURL = cvs.toDataURL(`image/${fileType}`, quality) // 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
          resolve(this.base64toFile(dataURL, filename))
        }
      })
    },
    base64toFile(dataurl, filename) {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      let file = new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      })
      return file
    },
    async save(data) {
      console.log(data)
      // let formData = new FormData()
      // formData.append('title', data.title)
      // formData.append('desc', data.desc)
      // formData.append('report_type', 'war')
      // for (let i = 0; i < this.fileList.length; i++) {
      //   console.log(this.fileList[i].raw);
      //   if (this.fileList[i].raw) {
      //     formData.append('files', this.fileList[i].raw)
      //   }
      // }
      // if(this.isAdd){
      //   formData.append("parent_id", '123');
      //   let [res, err] = await postAddBattleReport(formData)
      //   if (err) return this.$message.error("请求失败")
      //   if (res?.code == 201) {
      //     this.$refs.operationalReportForm.reset()
      //   }
      // }else {
      //   formData.append("report_id", this.form.report_id);
      // }
    },
    inputBoxEditCancelFiles(fileList) {
      this.fileList = fileList
      this.$refs.operationalReportForm.fileListData(fileList)
    },
    onChange(file, fileList) {
      console.log('347', file, fileList)
      let fileTypeResults = this.ImageFormat.some(
        (item) => item == file.name.split('.')[1]
      )
      if (!fileTypeResults) {
        console.log('339', file, fileList)
        let fileListResult = fileList.indexOf((item) => {
          if (item.raw.name == file.name) {
            return true
          }
        })
        fileList.splice(fileListResult, 1)
        return this.$message.error(`请上传${this.acceptType}类型的文件`)
      } else {
        if (this.isAdd) {
          this.fileList = fileList
          this.$refs.operationalReportForm.fileListData(fileList)
        } else {
          this.backFileList.push({ raw: file.raw, url: file.url })
          this.$refs.operationalReportForm.fileListData(fileList)
          console.log(this.backFileList)
        }
      }
    },
    //点击文件列表中已上传的文件时的钩子
    onPreview(file) {
      console.log('el-upload的点击文件列表中已上传的文件时的钩子', file)
      this.dialogImageUrl = file.url
      this.lookDialogVisible = true
      var img = new Image()
      // 改变图片的src
      img.src = file.url
      if (img.width <= 300) {
        this.lookDialogVisibleWidth = img.width * 10
      } else if (img.width <= 500) {
        this.lookDialogVisibleWidth = img.width * 2
      } else if (img.width <= 1500) {
        this.lookDialogVisibleWidth = img.width
      } else {
        this.lookDialogVisibleWidth = 1500
      }
    },
    onRemove(file, fileList) {
      if (!this.isAdd) {
        let removeData = this.backFileList.findIndex((item) => {
          if (item.raw.name == file.raw.name) {
            return true
          }
        })
        console.log('removeData', removeData)
        this.backFileList.splice(removeData, 1)
        this.$refs.operationalReportForm.fileListData(this.backFileList)
      }
      this.$refs.operationalReportForm.fileListData(fileList)
    },
  },
}
</script>

<style lang="less" scoped>
@import url('~@/assets/less/pop_up_style.less'); //弹窗样式

.btn_groups {
  color: #fff;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;

  div {
    width: 120px;
    height: 45px;
    line-height: 45px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
  }

  .cancel {
    margin-right: 20px;
    background-color: rgb(0, 117, 169);

    img {
      margin-right: 10px;
      width: 22px;
      height: 22px;
    }
  }
}
</style>
